package org.demo.jetty;

import com.ximalaya.xdcs.client.config.XdcsPropertiesParser;
import com.ximalaya.xdcs.spring.healthcheck.HealthcheckServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Task健康检查。XDCS 健康检查是通过配置servlet，如果有TOMCAT容器，直接配置即可。
 * 如果应用没有依赖tomcat，这个类会启动一个轻量级的jetty容器。
 *
 * @author junying.han
 */
public class TaskHeathCheckServer {

    private Server jettyServer;
    private int port;
    private static Logger logger = LoggerFactory.getLogger(TaskHeathCheckServer.class);

    /**
     * 构造方法
     *
     * @param port
     */
    public TaskHeathCheckServer(int port) {
        this.port = port;
    }

    /**
     * 启动。
     */
    public void start() {
        String appName = XdcsPropertiesParser.getApp();
        if (appName == null || appName.isEmpty()) {
            logger.error("appName is empty, HealthCheck may not be available.");
        }
        jettyServer = new Server(port);
        logger.info("init XDCS healthcheck with path '/{}/healthcheck' on port:{} ", appName, port);
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/" + appName);
        jettyServer.setHandler(context);
        context.addServlet(new ServletHolder(new HealthcheckServlet()), "/healthcheck");
        try {
            jettyServer.start();
            logger.info("jetty server start");
            while (!jettyServer.isStarted()) {
                Thread.sleep(500);
            }
        } catch (Exception ex) {
            logger.error("Error starting Jetty. HealthCheck may not be available.", ex);
        }

    }

    /**
     * 停服
     */
    public void stop() {
        try {
            jettyServer.stop();
            jettyServer.join();
        } catch (Exception ex) {
            logger.error("Error stopping Jetty. HealthCheck may not be available.", ex);
        }

    }

}

